package com.zhongkun.datahome.service.service.impl;

import com.zhongkun.datahome.common.core.domain.entity.SysUser;
import com.zhongkun.datahome.common.core.domain.entity.TenantUser;
import com.zhongkun.datahome.common.core.domain.model.LoginUser;
import com.zhongkun.datahome.common.exception.ServiceException;
import com.zhongkun.datahome.common.utils.SecurityUtils;
import com.zhongkun.datahome.core.mapper.SysUserMapper;
import com.zhongkun.datahome.core.repository.TenantUserRepository;
import com.zhongkun.datahome.core.service.ISysUserService;
import com.zhongkun.datahome.service.domain.CustomerBase;
import com.zhongkun.datahome.service.domain.CustomerFamily;
import com.zhongkun.datahome.service.repository.CustomerBaseRepository;
import com.zhongkun.datahome.service.repository.CustomerFamilyRepository;
import com.zhongkun.datahome.service.req.cmd.family.CustomerFamilyCmd;
import com.zhongkun.datahome.service.req.qry.family.CustomerFamilyQry;
import com.zhongkun.datahome.service.res.family.CustomerFamilyVo;
import com.zhongkun.datahome.service.service.ICustomerFamilyService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 客户家庭Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-04-14
 */
@Service
public class CustomerFamilyServiceImpl implements ICustomerFamilyService {
    @Resource
    private CustomerFamilyRepository customerFamilyRepository;

    @Resource
    private CustomerBaseRepository customerBaseRepository;

    @Resource
    private TenantUserRepository tenantUserRepository;

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    public List<CustomerFamilyVo> listMembers(CustomerFamilyQry qry) {
        CustomerFamily family = customerFamilyRepository.getById(qry.getFamilyId());
        List<CustomerBase> members = customerBaseRepository.getMemberByFamilyId(qry.getFamilyId());

        if (Objects.isNull(family) || CollectionUtils.isEmpty(members)) {
            return Collections.emptyList();
        }

        return members.stream().map(member -> CustomerFamilyVo.of(family, member)).collect(Collectors.toList());
    }

    @Override
    public Long addMember(CustomerFamilyCmd cmd) {
        if (StringUtils.isBlank(cmd.getMobile())) {
            throw new ServiceException("手机号码不能为空");
        }

        checkMobile(cmd);

        Long tenantUserId = tenantUserRepository.createTenantUser(cmd.getMobile(), cmd.getCustomerName());
        CustomerBase customerBase = CustomerBase.ofMember(cmd);
        customerBase.setTenantUserId(tenantUserId);
        customerBaseRepository.save(customerBase);
        return customerBase.getId();
    }

    @Override
    public void editMember(CustomerFamilyCmd cmd) {
        CustomerBase member = customerBaseRepository.getById(cmd.getCustomerId());
        if (Objects.isNull(member)) {
            throw new ServiceException("成员不存在");
        }

        if (!StringUtils.equals(cmd.getMobile(), member.getMobile())) {
            checkMobile(cmd);
        }

        // 同步修改系统用户
        SysUser user = sysUserMapper.selectUserByUserName(cmd.getMobile(), null);
        if (!Objects.equals(user.getNickName(), cmd.getCustomerName())) {
            user.setNickName(cmd.getCustomerName());
            sysUserMapper.updateUser(user);
        }
        member.updateMember(cmd);
        customerBaseRepository.updateById(member);
    }

    @Override
    @Transactional
    public void removeMember(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return;
        }

        // 删除成员 客户/商户/用户信息
        ids.forEach(id -> {
            CustomerBase customerBase = customerBaseRepository.getById(id);
            if (Objects.isNull(customerBase)) {
                return;
            }

            customerBaseRepository.removeById(id);
            TenantUser tenantUser = tenantUserRepository.getById(customerBase.getTenantUserId());
            sysUserService.deleteTokenUserById(tenantUser.getUserId());

            SysUser sysUser = sysUserService.selectUserById(tenantUser.getUserId());
            if (Objects.nonNull(sysUser) && CollectionUtils.isEmpty(sysUser.getRoles())) {
                sysUserService.deleteUserById(sysUser.getUserId());
            }
        });
    }

    @Override
    public List<CustomerBase> listMembersForApp() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (Objects.isNull(loginUser) || Objects.isNull(loginUser.getTenantUserId())) {
            throw new ServiceException("用户未登陆");
        }

        return customerBaseRepository.getMemberByTenantUserId(loginUser.getTenantUserId());
    }

    private void checkMobile(CustomerFamilyCmd cmd) {
        CustomerBase byMobile = customerBaseRepository.getByMobile(cmd.getMobile());
        if (Objects.nonNull(byMobile)) {
            if (!Objects.equals(cmd.getFamilyId(), byMobile.getFamilyId())) {
                throw new ServiceException("当前成员属于其他家庭");
            }

            throw new ServiceException("家庭成员已存在");
        }
    }
}
